1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
|
import dynamic from 'next/dynamic'
import { useEffect, useState } from 'react'
import { useRouter } from 'next/router'
import Seo from '../../../core/components/Seo'
import Promocrumb from '../../../lib/promo/components/Promocrumb'
import { fetchPromoItemsSolr } from '../../../api/promoApi'
import LogoSpinner from '../../../core/components/elements/Spinner/LogoSpinner.jsx'
import ProductPromoCard from '../../../../src-migrate/modules/product-promo/components/Card'
import { IPromotion } from '../../../../src-migrate/types/promotion'
import React from 'react'
import { SolrResponse } from "../../../../src-migrate/types/solr.ts";
import { Swiper, SwiperSlide } from 'swiper/react';
import 'swiper/swiper-bundle.css';
import useDevice from '../../../core/hooks/useDevice'
const BasicLayout = dynamic(() => import('../../../core/components/layouts/BasicLayout'))
export default function PromoDetail() {
const router = useRouter()
const { slug = '' } = router.query
const [promoItems, setPromoItems] = useState<any[]>([])
const [promoData, setPromoData] = useState<IPromotion[] | null>(null)
const [currentPage, setCurrentPage] = useState(1);
const itemsPerPage = 12; // Jumlah item yang ingin ditampilkan per halaman
const startIndex = (currentPage - 1) * itemsPerPage;
const endIndex = Math.min(startIndex + itemsPerPage, promoData?.length || 0);
const [loading, setLoading] = useState(true);
const [fetchingData, setFetchingData] = useState(false)
const { isMobile, isDesktop } = useDevice()
useEffect(() => {
const loadPromo = async () => {
try {
const items = await fetchPromoItemsSolr(`type_value_s:${Array.isArray(slug) ? slug[0] : slug}`)
console.log("slug sekarang ", slug)
setPromoItems(items)
console.log("data dari promotion pakai SOLR", items)
if (items.length === 0) {
setPromoData([])
setLoading(false);
return;
}
const promoDataPromises = items.map(async (item) => {
const queryParams = new URLSearchParams({ q: `id:${item.id}` })
console.log("Constructed URL:", `/solr/promotion_program_lines/select?${queryParams.toString()}`)
try {
const response = await fetch(`/solr/promotion_program_lines/select?${queryParams.toString()}`)
console.log("respon data ", response)
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`)
}
const data: SolrResponse<any[]> = await response.json()
console.log("data promo IPromotion[]", data)
const promotions = await map(data.response.docs)
return promotions;
} catch (fetchError) {
console.error("Error fetching promotion data:", fetchError)
return [];
}
});
const promoDataArray = await Promise.all(promoDataPromises);
const mergedPromoData = promoDataArray.reduce((accumulator, currentValue) => accumulator.concat(currentValue), []);
setPromoData(mergedPromoData);
setTimeout(() => setLoading(false), 120); // Menambahkan delay 120ms sebelum mengubah status loading
} catch (loadError) {
console.error("Error loading promo items:", loadError)
setLoading(false);
}
}
if (slug) {
loadPromo()
}
}, [slug])
useEffect(() => {
window.scrollTo({ top: 0, behavior: 'auto' }); // Auto scroll to top when component mounts or updates
}, []); // Run only once when component mounts
const map = async (promotions: any[]): Promise<IPromotion[]> => {
const result: IPromotion[] = []
for (const promotion of promotions) {
const data: IPromotion = {
id: promotion.id,
program_id: promotion.program_id_i,
name: promotion.name_s,
type: {
value: promotion.type_value_s,
label: promotion.type_label_s,
},
limit: promotion.package_limit_i,
limit_user: promotion.package_limit_user_i,
limit_trx: promotion.package_limit_trx_i,
price: promotion.price_f,
total_qty: promotion.total_qty_i,
products: JSON.parse(promotion.products_s),
free_products: JSON.parse(promotion.free_products_s),
}
result.push(data)
}
return result
}
console.log("data yg dikirim ke ProductPromoCard", promoData)
function capitalizeFirstLetter(string) {
// Ganti semua tanda _ dengan spasi
string = string.replace(/_/g, ' ');
// Kapitalisasi huruf pertama setelah spasi atau awal string
return string.replace(/(^\w|\s\w)/g, function(match) {
return match.toUpperCase();
});
}
useEffect(() => {
const handleScroll = () => {
if (
!fetchingData &&
window.innerHeight + document.documentElement.scrollTop >= 0.95 * document.documentElement.offsetHeight
) {
// User has scrolled to 95% of page height
setTimeout(() => setFetchingData(true), 120);
setCurrentPage((prevPage) => prevPage + 1)
}
}
window.addEventListener('scroll', handleScroll)
return () => window.removeEventListener('scroll', handleScroll)
}, [fetchingData])
useEffect(() => {
if (fetchingData) {
// Fetch more data
// You may need to adjust this logic according to your API
fetchMoreData()
}
}, [fetchingData])
const fetchMoreData = async () => {
try {
// Add a delay of approximately 150ms
setTimeout(async () => {
// Fetch more data
// Update promoData state with the new data
}, 150)
} catch (error) {
console.error('Error fetching more data:', error)
} finally {
setTimeout(() => setFetchingData(false), 120);
}
}
const visiblePromotions = promoData?.slice(0, currentPage * 12)
return (
<BasicLayout>
<Seo
title={`Promo ${Array.isArray(slug) ? slug[0] : slug} Terkini`}
description='B2B Marketplace MRO & Industri dengan Layanan Pembayaran Tempo, Faktur Pajak, Online Quotation, Garansi Resmi & Harga Kompetitif'
/>
<Promocrumb brandName={capitalizeFirstLetter(Array.isArray(slug) ? slug[0] : slug)} />
{loading ? (
<div className='container flex justify-center my-4'>
<LogoSpinner width={48} height={48} />
</div>
) : promoData && promoItems.length >= 1 ? (
<>
<Swiper slidesPerView={isMobile? 1:4.7} spaceBetween={10} freeMode={true}>
<div className=' relative bg-slate-900'>
{visiblePromotions?.map((promotion) => (
<SwiperSlide className='' key={promotion.id}>
<div className="min-w-[400px] max-w-[400px] mb-[20px] sm:w-full md:w-1/2 lg:w-1/3 xl:w-1/4">
<ProductPromoCard promotion={promotion}/>
</div>
</SwiperSlide>
))}
</div>
</Swiper>
</>
) : (
<div className="text-center my-8">
<p>Belum ada promo pada kategori ini</p>
</div>
)}
</BasicLayout>
)
}
|